import { get, set } from 'lodash';
const setCellType = (cell, toCell) => {
    try{
        const cellType = cell.cellType();
        if (cellType.typeName) {
            const CellTypeClass = window[cellType.typeName];
            if (CellTypeClass) {
                let cellTypeInstance = new CellTypeClass();
                cellTypeInstance.fromJSON(cellType);
                toCell.cellType(cellTypeInstance);
                if(cellType.vierAttr !=1)
                    toCell.locked(false);
            }
        }
    } catch(e) {
        console.log(e)
    }
    
}

const getFieldName = (bindingPath) => {

    let strs = bindingPath.split(".");
    return strs[strs.length - 1];

}

const getCurrentT = (bindingPath) => {

    let strs = bindingPath.split(".");
    return strs[2];

}

const relatedChildFun = (relatedChild, childValues, value, cellType, sheet, row, cellcol, cCol) => {
    const cvalues = childValues ? childValues.split(",") : undefined;
    const expandType = cellType.expandType;
    // 纵向扩展
    if (expandType == '2') {

        let rowcount = 1;
        // 纵向扩展的合并单元格
        const span = sheet.getSpan(row, cellcol);
        if (span) {
            rowcount = span.rowCount;
        }

        let targetRow;
        const c = cCol;

        if (!targetRow) {

            for (let r = 0; r < rowcount; r++) {
                const childCell = sheet.getCell(row + r, c);
                const cCelltype = childCell.cellType();
                // 获取到关联的子下拉框
                if (childCell.bindingPath() && cCelltype && cCelltype.typeName == 'WeaSelectCellType'
                    && getFieldName(childCell.bindingPath()) == relatedChild) {
                    let newItems = [];
                    if (cvalues) {
                        newItems = cCelltype.fieldType[2].datas.filter(r =>
                            cvalues.indexOf(r.selectName) > -1
                        );
                    } else if (value) {
                    } else {
                        // 父字段没有值，子字段也不能选
                        //newItems = cellType.fieldType[2].datas;
                    }

                    if (newItems.length == 0 && childCell.value()) {
                        childCell.value(undefined);
                    } else {
                        if (newItems.filter(r => r.selectValue == childCell.value()).length < 1) {
                            if (childCell.value()) {
                                childCell.value(undefined);
                            }
                        }
                    }
                    cCelltype.items(newItems.map((d) => ({ text: d.selectName, value: '' + d.selectValue })));
                }
            }

        } else {

            // 后期如果行数很多，可以考虑根据目标行来减少循环
        }


    }

}

export default {
    canUndo: true,
    execute: (context, options, isUndo) => {
        context.suspendPaint();
        try {
            const { table, store, col: currentCol, sheet, sheetName, oldDelete, insertType, insertColCount, downExpandCount, expandStartRow } = options;
            const bindingPath = table.bindingPath();
            if (isUndo) {
                const {
                    name, row, col, rowCount, colCount, bindingPath, cCol, insertColCount, currentT,expandT, preBindPath
                } = options.old;
                const ct = store.customBindingCurrentT[preBindPath];
                const source = store.dataSourceInstance.getSource();
                for (let i = ct; i > currentT; i--) {
                    delete source[`${sheetName}`]["custom_" + table.name().substring("custom".length)][`${'t' + i}`];
                }
                sheet.deleteColumns(cCol, insertColCount);
                sheet.tables.resize(table, rowCount, colCount);

                options._oldSpan.forEach(range => {
                    sheet.addSpan(range.row, range.col, range.rowCount, range.colCount);
                });
                store.customBindingCurrentT[preBindPath] = currentT;
                //store.customExpandCurrent[preBindPath] = expandT;
            } else {
                const { row, rowCount, col, colCount } = table.dataRange();
                let num = 0;
                let num1 = insertColCount;
                if (insertType == 'right') {
                    num = insertColCount;
                    num1 = 0;
                }

                const preBindPath = sheet.name() + ".custom_" + table.name().substring("custom".length);
                let currentT = store.customBindingCurrentT[preBindPath];
                let expandT = store.customExpandCurrent[preBindPath];
                options.old = {
                    name, row, col, rowCount, colCount, bindingPath, cCol: currentCol + num, insertColCount, currentT,expandT, preBindPath

                };

                options._oldSpan = [];
                for (let r = 0; r < rowCount; r++) {
                    const cr = r + row;
                    for (let c = 0; c < colCount; c++) {
                        const cc = c + col;
                        const span = sheet.getSpan(cr, cc);
                        if (span && cr == span.row && cc == span.col) {
                            options._oldSpan.push(span);
                        }
                    }
                }

                // 先resize再赋值
                sheet.addColumns(currentCol + num, insertColCount);
                sheet.tables.resize(table, rowCount, colCount + insertColCount);
                sheet.setColumnWidth(currentCol + num, sheet.getColumnWidth(currentCol + num1));
                const expandFieldMap = store.customExpandFieldname[preBindPath];

                const beforespans = [];
                const tmpc = currentCol + num1;
                for(let r = 0 ; r < rowCount; r++) {
                    const cr = r+ row;
                    const span = sheet.getSpan(cr,tmpc);
                    if(span && span.colCount > insertColCount) {

                        beforespans.push(span)
                        sheet.removeSpan(cr,tmpc);
                    }
                }


                sheet.copyTo(row, currentCol + num1, row, currentCol + num, rowCount, insertColCount, GC.Spread.Sheets.CopyToOptions.all);

                if(beforespans.length > 0) {
                    beforespans.forEach(span => {

                        sheet.addSpan(span.row , span.col < currentCol + num ? span.col: currentCol + num, 
                            span.rowCount, span.col < currentCol + num ?span.colCount : span.colCount + insertColCount);
                    })
                }

                // 新增块首行
                const startCol = currentCol + num;
                const downlist = [];
                const celllist = [];
                const cellvaluelist = [];
                const downColNum = [];
                const spans = [];

                const rightExpandCurrentT = currentT + 1;
                // 逐个绑定
                for (let i = 0; i < rowCount; i++) {
                    const cRow = row + i;
                    const span = sheet.getSpan(cRow, startCol);
                    let cell
                    let value;
                    if (span) {
                        cell = sheet.getCell(span.row, span.col);
                        value = cell.value();
                    } else {
                        cell = sheet.getCell(cRow, startCol)
                    }
                    const cellType = cell.cellType();

                    // 横向共通扩展行
                    if (cellType && cellType.expandType == '1' && cRow < expandStartRow) {
                        const fieldname = getFieldName(cell.bindingPath());
                        if(expandFieldMap.indexOf(fieldname) > -1) {
                            expandT = expandT + 1;
                            cell.bindingPath(preBindPath+'h' + ".t" + expandT + "." + fieldname);
                        } else {
                            cell.bindingPath(preBindPath + ".t" + rightExpandCurrentT + "." + fieldname);
                        }
                        
                        setCellType(sheet.getCell(cRow, startCol), cell);
                        downlist.push(fieldname);
                        celllist.push(cell);
                        cellvaluelist.push(value)
                        downColNum.push(cRow);
                        spans.push(span);
                        continue;
                    } 
                    //(有可能没有设置，这种情况也先考虑下)
                    else if (cellType && cRow < expandStartRow) {
                        const fieldname = getFieldName(cell.bindingPath());
                        if(expandFieldMap.indexOf(fieldname) > -1) {
                            expandT = expandT + 1;
                            cell.bindingPath(preBindPath+'h' + ".t" + expandT + "." + fieldname);
                        } else {
                            cell.bindingPath(preBindPath + ".t" + rightExpandCurrentT + "." + fieldname);
                        }
                        setCellType(sheet.getCell(cRow, startCol), cell);
                        downlist.push(fieldname);
                        celllist.push(cell);
                        cellvaluelist.push(value)
                        downColNum.push(cRow);
                        spans.push(span);
                        continue;
                    }

                    //for(let j = 0 ; j < insertRowCount; j++ ) {
                    //const cellType = cell.cellType();
                    if ((cRow - expandStartRow) % downExpandCount == 0) {
                        currentT = currentT + 1;

                        store.dataSourceInstance.setValue(preBindPath + ".t" + currentT, JSON.parse(JSON.stringify(store.dataSourceInstance.getValue(preBindPath + "." + getCurrentT(sheet.getCell(cRow, currentCol).bindingPath())))));
                        downlist.forEach(fieldname => {
                            store.dataSourceInstance.setValue((preBindPath + ".t" + currentT + "." + fieldname), '');
                        })
                    }
                    if (cellType) {
                        // if(j == 0) {
                        //     currentT = currentT + 1;
                        //     store.dataSourceInstance.setValue(preBindPath+".t" + currentT,JSON.parse(JSON.stringify(store.dataSourceInstance.getValue(preBindPath+"." + getCurrentT(sheet.getCell(currentRow,cCol).bindingPath())))));
                        //     downlist.forEach(fieldname => {
                        //         store.dataSourceInstance.setValue((preBindPath+".t" + currentT+"."+ fieldname),'');
                        //     })
                        // }

                        store.dataSourceInstance.setValue((preBindPath + ".t" + currentT + "." + getFieldName(cell.bindingPath())), '');
                        cell.bindingPath(preBindPath + ".t" + currentT + "." + getFieldName(cell.bindingPath()));
                        setCellType(sheet.getCell(cRow, currentCol + num1), cell);
                    }
                    //}

                }
                celllist.forEach((cell,index) => {
                    const{row, col} = cell;
                    const span = sheet.getSpan(row,col);
                    if(span && span.colCount > insertColCount) {
                        sheet.getCell(span.row, span.col).value(cellvaluelist[index])
                    } else {

                        cell.value(undefined);
                    }
                })
                // 新增行后，有时候span不起作用，此处对span再设置下

                // for(let r = startRow ; r < row + rowCount ; r = r + insertRowCount) {
                //     for(let i = 0 ; i < downColNum.length; i++) {

                //         const span = sheet.getSpan(r, downColNum[i]);
                //         if(!span) {
                //             const s = spans[i];
                //             sheet.addSpan(r, downColNum[i],s.rowCount, s.colCount);
                //         }
                //     }
                // }

                // 纵向的需要处理下，处理联动情况
                const {row:tablerow, rowCount:tablerowCount, col:tablecol, colCount:tablecolCount} = table.dataRange();
                for (let r = tablerow; r < tablerow + tablerowCount; r++) {
                    const row = r;
                    for (let c = tablecol; c < tablecol + tablecolCount; c++) {
                        const col = c;
                        const cell = sheet.getCell(row, col);
                        const cellType = cell.cellType();
                        const newValue = cell.value();
                        if (cellType && cellType.expandType == 2) {
                            const filedType = cellType.fieldType;
                            if (filedType && filedType[2]) {
                                const relatedChild = filedType[2].relatedChild;
                                const datas = filedType[2].datas;


                                if (relatedChild) {
                                    // 下拉框选择的值
                                    const selectValue = datas.filter(r => r.selectValue == newValue)[0];
                                    // 选择框有值时
                                    if (selectValue && newValue) {

                                        relatedChildFun(relatedChild, selectValue.childValue, newValue, cellType, sheet, row, col, currentCol + num);
                                    } else {
                                        relatedChildFun(relatedChild, undefined, undefined, cellType, sheet, row, col, currentCol + num);
                                    }
                                }
                            }
                        }

                    }
                }
                // 合并行赋值
                // for (let i = 0; i < rowCount; i++) {
                //     const cRow = row + i;
                //     const span = sheet.getSpan(cRow, startCol);
                //     if(span) {
                //         const {row, col} = span;
                //         const value = sheet.getCell(row, col).value();
                //         console.log(value,row, startCol,"值")
                //         sheet.getCell(row, startCol).value('-999');
                //         sheet.getCell(row, startCol).value(value);
                //     }
                // }



                store.customBindingCurrentT[preBindPath] = currentT;
                store.customExpandCurrent[preBindPath] = expandT;

            }
            // table.bindingPath(bindingPath);
            store.calcAll(true, sheetName);
        } catch (e) {
            if (!!(window.console && window.console.log)) {
                window.console.log(e);
            }
            console.log(e)
        }
        context.resumePaint();
    }
};